package clients

import (
	"bytes"
	"encoding/json"
	"finance/config"
	"fmt"
	"io"
	"net/http"
)

// DeepSeekMessage 是 API 消息结构
type DeepSeekMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

// DeepSeekRequest 是完整请求体
type DeepSeekRequest struct {
	Model    string            `json:"model"`
	Messages []DeepSeekMessage `json:"messages"`
	Stream   bool              `json:"stream"`
}

// DeepSeekResponse 用于解析返回结果
type DeepSeekResponse struct {
	Choices []struct {
		Message struct {
			Content string `json:"content"`
		} `json:"message"`
	} `json:"choices"`
}

// AnalyzeLogsWithDeepSeek 调用 DeepSeek API 分析日志
func AnalyzeLogsWithDeepSeek(logs string) (string, error) {
	apiKey := config.AppConfig.DeepSeek.ApiKey
	if apiKey == "" {
		return "", fmt.Errorf("missing DEEPSEEK_API_KEY environment variable")
	}

	request := DeepSeekRequest{
		Model: "deepseek-chat",
		Messages: []DeepSeekMessage{
			{Role: "system", Content: "You are a cybersecurity auditor analyzing potential security risks in banking system logs."},
			{Role: "user", Content: fmt.Sprintf("Analyze these logs and summarize any potential risks or abnormal behaviors:\n%s", logs)},
		},
		Stream: false,
	}

	data, _ := json.Marshal(request)
	req, _ := http.NewRequest("POST", "https://api.deepseek.com/v1/chat/completions", bytes.NewReader(data))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close() //

	body, _ := io.ReadAll(resp.Body)
	var result DeepSeekResponse
	if err := json.Unmarshal(body, &result); err != nil {
		return "", err
	}

	if len(result.Choices) == 0 {
		return "", fmt.Errorf("empty response from DeepSeek")
	}

	return result.Choices[0].Message.Content, nil
}
